﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using KOPLibrary.DataManagement;
using Microsoft.Office.Interop.Word;

namespace KOPLibrary.Forms
{
    public partial class BindWordTemplateForm : Form
    {
        private AbstractData Data = null;
        private string password = null;
        bool cancel = false;
        public BindWordTemplateForm(AbstractData data)
        {
            InitializeComponent();
            InitUI(data);
        }



        private void InitUI(AbstractData data)
        {
            Data = data;
            ctlAutoSavePanel.Visible = false;
            ctlFileNameSetPanel.Visible = false;
            ctlFileNameType.SelectedIndex = 0;
            ctlFileNameType_SelectedIndexChanged(null, new EventArgs());
            ctlExcelData.DataSource = data.Columns.ToArray();
            ctlStartNumber.Minimum = 0;
            ctlStartNumber.Maximum = decimal.MaxValue;
            ctlStartNumber.Value = 0;
        }

        private void ctlGetTemplate_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Word Belgeleri ve Şablonları|*.docx;*.dotx";
                ofd.Title = "Hatırlama Geçmişi Al";
                ofd.InitialDirectory = PreferenceManagement.PreferenceManager.GetDefaulTemplatePath(TemplateManagement.TemplateType.Word);
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    ctlTemplatePath.Text = "Belge : " + Path.GetFileNameWithoutExtension(ofd.FileName);
                    ctlTemplatePath.Tag = ofd.FileName;
                }
            }
        }

        private void ctlTemplatePath_MouseHover(object sender, EventArgs e)
        {
            if (ctlTemplatePath.Tag != null)
                ctltooltipTemplate.Show(ctlTemplatePath.Tag.ToString(), this, ctlTemplatePath.Left + 15, ctlTemplatePath.Top + ctlTemplatePath.Height + 25);
        }

        private void ctlAutoSave_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                ctlAutoSavePanel.Visible = true;
                ctlFileNameType_SelectedIndexChanged(null, new EventArgs());
            }
            else
            {
                ctlAutoSavePanel.Visible = false;
                ctlFileNameSetPanel.Visible = false;
            }
        }

        private void ctlFileNameType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ctlFileNameSetPanel.Visible = true;
            if (ctlFileNameType.SelectedIndex == 0)
            {
                ctlStartNumberPanel.Visible = true;
                ctlExcelDataPanel.Visible = false;
            }
            else
            {
                ctlStartNumberPanel.Visible = false;
                ctlExcelDataPanel.Visible = true;
            }

        }

        private void ctlTemplatePath_MouseLeave(object sender, EventArgs e)
        {
            ctltooltipTemplate.Hide(this);
        }

        private void ctlOk_Click(object sender, EventArgs e)
        {
            if (ctlTemplatePath.Tag == null)
            {
                MessageBox.Show("Şablon belge seçiniz", "Uyarı");
                return;
            }
            else
            {
                if (!File.Exists(ctlTemplatePath.Tag.ToString()))
                {
                    MessageBox.Show("Seçilen dosya diskte bulunamadı", "Uyarı");
                    return;
                }
            }
            if (ctlAutoPrint.Checked)
            {
                if (!(new GreenForm().Execute()))
                    return;
            }
            if (ctlAutoSave.Checked)
            {
                if (string.IsNullOrEmpty(ctlFolderPath.Text.Trim()))
                {
                    MessageBox.Show("Kaydedilecek klasör yolu boş olamaz", "Uyarı");
                    return;
                }
                if (!Directory.Exists(ctlFolderPath.Text.Trim()))
                {
                    MessageBox.Show("Seçilen klasör mevcut veya erişim izni yok", "Uyarı");
                    return;
                }
            }
            cancel = false;
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();            
            Microsoft.Office.Interop.Word.Document doc = null;
            WordManager wm = new WordManager(app);
            ProgressForm pf = new ProgressForm();
            pf.Cancel += new EventHandler(processcancel);
            int tempindex;
            object tempfilename;
            string temppath;

            if (ctlAutoSave.Checked)
            {
                pf.Initialize(1, Data.Count, "Dosyalar hazırlanıp kaydediliyor", true, this);
                app.Visible = false;
                //List<ContentControl> controls = wm.GetContentControlsFromDoc(doc, true);
                for (int i = 0; i < Data.ItemArray.Count; i++)
                {
                    if (cancel) break;
                    doc = app.Documents.Add(Template: ctlTemplatePath.Tag.ToString(), Visible: false);
                    wm.BindDocument(doc, Data, i);
                    if (ctlFileNameType.SelectedIndex == 0)
                    {
                        temppath = ctlFolderPath.Text.Trim() + "\\" + (ctlStartNumber.Value + i).ToString();
                        pf.Update(temppath);
                        try
                        {
                            doc.SaveAs(temppath, Password: password ?? Type.Missing);
                        }
                        catch { ;}

                    }
                    else
                    {
                        tempindex = Data.Columns.IndexOf(ctlExcelData.SelectedItem.ToString());
                        tempfilename = Data.ItemArray[i][tempindex] ?? i.ToString();
                        tempfilename = Util.NormalizeFileName(tempfilename.ToString(), i.ToString());
                        pf.Update(tempfilename.ToString());
                        try
                        {
                            doc.SaveAs(ctlFolderPath.Text.Trim() + "\\" + tempfilename.ToString(), Password: password ?? Type.Missing);
                        }
                        catch { ;}
                    }
                }
                pf.Done();
                doc.Application.Quit(SaveChanges: false);
            }
            else if (ctlAutoOpen.Checked)
            {
                app.Visible = false;
                pf.Initialize(1, Data.ItemArray.Count, "Dosyalar hazırlanıp açılıyor", true, this);
                for (int i = 0; i < Data.ItemArray.Count; i++)
                {
                    if (cancel) break;
                    pf.Update(string.Format("{0}/{1} işleniyor", i+1, Data.ItemArray.Count));
                    doc = app.Documents.Add(Template: ctlTemplatePath.Tag.ToString());
                    wm.BindDocument(doc, Data, i);
                }
                pf.Done();
                app.Visible = true;
                app.ShowMe();

            }
            else if (ctlAutoPrint.Checked)
            {
                app.Visible = true;
                pf.Initialize(1, Data.ItemArray.Count, "Dosyalar hazırlanıp açılıyor", true, this);
                for (int i = 0; i < Data.ItemArray.Count; i++)
                {
                    if (cancel) break;
                    {
                        pf.Update(string.Format("{0}/{1} yazdırılıyor", i, Data.ItemArray.Count));
                        doc = app.Documents.Add(Template: ctlTemplatePath.Tag.ToString(), Visible: false);
                        wm.BindDocument(doc, Data, i);
                        doc.Activate();
                        doc.PrintOut(Background: false);
                    }
                }
                pf.Done();
                doc.Application.Quit(SaveChanges: false);
            }
        }

        void processcancel(object sender, EventArgs e)
        {
            cancel = true;
        }

        private void ctlGenerateForm_Click(object sender, EventArgs e)
        {
            if (Data != null)
            {
                TemplateDesigner form = new TemplateDesigner(null, KOPLibrary.TemplateManagement.TemplateType.Excel, Data, true);
                form.ShowDialog();
            }
        }

        private void ctlGetDirectory_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                fbd.RootFolder = Environment.SpecialFolder.Desktop;
                fbd.ShowNewFolderButton = true;
                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ctlFolderPath.Text = fbd.SelectedPath;
                }
            }
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }


        private void ctlPasswordTrustedSecure_Click(object sender, EventArgs e)
        {
            password = ProtectDocument.ExecuteProtectDocument(TemplateManagement.TemplateType.Word);
        }
    }
}
